package com.dhq.services;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import org.apache.solr.client.solrj.SolrQuery;
import org.apache.solr.client.solrj.SolrServer;
import org.apache.solr.client.solrj.SolrServerException;
import org.apache.solr.client.solrj.impl.HttpSolrServer;
import org.apache.solr.client.solrj.response.QueryResponse;
import org.apache.solr.common.SolrDocument;
import org.apache.solr.common.SolrDocumentList;
import com.dhq.utils.sqlserverUtils;

public class SearchAndInsert {
	public static void main(String[] args) throws SQLException, SolrServerException {
		int count=1;
		SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		SolrServer solr = new HttpSolrServer("http://localhost:8080/solr");
		Connection sqlServerConnection = sqlserverUtils.getSqlServerConnection(
				"files_library", "sa", "123456");
		PreparedStatement ps = sqlServerConnection.prepareStatement("select title,id from online_meta_part1");
		
		Connection con = sqlserverUtils.getSqlServerConnection(
				"files_library", "sa", "123456");
//		insert into blib_module_document (ChannelId,ClassId,Title, TColor, AddTime,AddDate,Summary, Editor,Author, Tags, ViewNum,  IsPass,  IsImg,  Img, IsTop,  IsFocus,  IsHead,  UserId,  ReadGroup,  SourceFrom,PageNumber,Points,  DocumentUrl_Old,DownNum,  PageSize, FirstPage, AliasPage, FileExt, FileSize, ZhongTuHao, ClassCode1,ClassCode2, Score, organization, guid, JournalName, fileid, UserName, isopen, filepath, CustomFieldValue2,CustomFieldValue3, DocumentUrl, IsOLD,  lastdownloadtime, CanView,  IsSuccess,  ErrTimes,  SuccessTime,FirstChar) values (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)
		PreparedStatement insertPS = con.prepareStatement("update online_meta_part1 set classify = ? where id= ?");
		
		ResultSet rs = ps.executeQuery();
		while(rs.next()){
			String docTitle = rs.getString("title");
			int docId=rs.getInt("id");
			
			SolrQuery query = new SolrQuery();
			
				//设置查询条件,名称“q”是固定的且必须 的
				query.set("q", "name:"+docTitle.replace(":", "").replace("：", ""));
				query.setStart(0);
				query.setRows(1);
				// 请求查询
				QueryResponse response;
				try {
					response = solr.query(query);
				} catch (Exception e) {
					continue;
				}

				// 查询结果
				SolrDocumentList documentList = response.getResults();
				for (SolrDocument doc : documentList) {
					String classify = (String) doc.getFieldValue("id");
					insertPS.setString(1, classify);
					insertPS.setInt(2, docId);
					insertPS.addBatch();
					count++;
				}
				if (count%5000==0) {
					insertPS.executeBatch();
					insertPS.clearBatch();
					System.out.println("count ： "+count +" "+df.format(System.currentTimeMillis()));
				}
			}
		
	}
}	
